<template>
  <div class="row">
      <h2 v-if="firstView">根据关键字收索GitHub用户名称</h2>
      <h2 v-else-if="loading">正在请求中请等待...</h2>
      <h2 v-else-if="errorMsg" :style="{color: hotpink}">{{errorMsg}}</h2>
    <div class="card" v-for="user in users" :key="user.userName">
      <a :href="user.url" target="_blank">
        <img
          :src="user.avatar_url"
          style="width: 100px"
        />
      </a>
      <p class="card-text">{{user.userName}}</p>
    </div>
  </div>
</template>

<script>
import axios from "axios"
export default {
  name: "Main",
  data(){
      return{
          firstView:true,
          loading:false,
          users:[],
          errorMsg:''
      }
  },
  mounted(){
      this.$bus.$on('search',this.search)
  },
  methods: {
      search(searchName){
          this.firstView = false;
          this.loading = true;
          axios.get(`https://api.github.com/search/users?q=${searchName}`)
          .then(response=>{
            //   请求成功，更新为成功状态
            this.loading = false;
            const data = response.data;
            const users = data.items.map(item=>({
                userName:item.login,
                url:item.html_url,
                avatar_url:item.avatar_url,
            }))
            this.users = users;
          })
          .catch(error=>{
            //   请求失败，更新失败状态
              this.loading = false;
              this.errorMsg = error.message;
              // alert(error.message);
              // console.log(error);
          })  
      }
  }
};
</script>

<style scoped>
.card {
  float: left;
  width: 33.333%;
  padding: 0.75rem;
  margin-bottom: 2rem;
  border: 1px solid #efefef;
  text-align: center;
}

.card > img {
  margin-bottom: 0.75rem;
  border-radius: 100px;
}

.card-text {
  font-size: 85%;
}
</style>
